package com.atguigu.gmall.common.inteceptor;

import com.atguigu.gmall.common.util.AuthContextHolder;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author: 李旭
 * @create: 2021-07-22 14:18
 * <p>
 * 远程调用 拦截器
 * 1、远程调用之前被下面的拦截器先拦截下来  处理之后 再发请求
 **/
//@Component
public class FeignInterceptor implements RequestInterceptor {


    //RequestTemplate : 即将马上发出的请求（远程调用对象)
    @Override
    public void apply(RequestTemplate requestTemplate) {
        System.out.println("页面微服务远程调用时被拦截了，进来了");//兼容  TCP HTTP
        // null
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes)
                RequestContextHolder.getRequestAttributes();
        if (null != requestAttributes) {
            HttpServletRequest request = requestAttributes.getRequest();
            if (null != request) {
                String userId = AuthContextHolder.getUserId(request);
                String userTempId = AuthContextHolder.getUserTempId(request);
                if (!StringUtils.isEmpty(userId)) {
                    //远程调用对象
                    requestTemplate.header("userId", userId);
                }
                if (!StringUtils.isEmpty(userTempId)) {
                    //远程调用对象
                    requestTemplate.header("userTempId", userTempId);
                }
            }
        }


    }
}
